package com.st.swagger.service;

import com.st.swagger.entity.Product;
import com.st.swagger.mapper.ProductMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
@Service
public class ProductService {

    @Autowired
    private ProductMapper productMapper;

    /**
     * 获取所有商品
     */
    public List<Product> getAllProducts() {
        return productMapper.findAll();
    }

    /**
     * 根据ID获取商品
     */
    public Product getProductById(Long id) {
        Product product = productMapper.findById(id);
        if (product == null) {
            throw new RuntimeException("商品不存在");
        }
        return product;
    }

    /**
     * 添加新商品
     */
    public Product createProduct(Product product) {
        productMapper.insertProduct(product);
        return product;
    }

    /**
     * 更新商品信息
     */
    public Product updateProduct(Long id, Product product) {
        Product existingProduct = productMapper.findById(id);
        if (existingProduct == null) {
            throw new RuntimeException("商品不存在");
        }
        product.setId(id);
        productMapper.updateProduct(product);
        return product;
    }

    /**
     * 删除商品
     */
    public void deleteProduct(Long id) {
        Product existingProduct = productMapper.findById(id);
        if (existingProduct == null) {
            throw new RuntimeException("商品不存在");
        }
        productMapper.deleteProduct(id);
    }

    /**
     * 根据关键字搜索商品
     */
    public List<Product> searchProducts(String keyword) {
        return productMapper.findByNameContaining(keyword);
    }
}

